#!/usr/bin/env bash

# Create a new directory and enter it
function mkd() {
    mkdir -p "$@" && cd "$_";
}

# Determine size of a file or total size of a directory
function fs() {
    if du -b /dev/null > /dev/null 2>&1; then
        local arg=-sbh;
    else
        local arg=-sh;
    fi
    if [[ -n "$@" ]]; then
        du $arg -- "$@";
    else
        du $arg ./*;
    fi;
}

# Use Git’s colored diff when available
hash git &>/dev/null;
if [ $? -eq 0 ]; then
    function diff() {
        git diff --no-index --color-words "$@";
    }
fi;

function grepx() {
    grep -nr $1 .
}

function rm-changed-host() {
    HOST=$1
    HOST_KEY_LINE=$(ssh-keygen -F "${HOST}" | tail -n1)
    if [ $? -ne 0 ]; then
        return 0
    fi

    KEY_TYPE=$(echo "${HOST_KEY_LINE}" | awk '{ print $2 }')
    HOST_KEY=$(echo "${HOST_KEY_LINE}" | awk '{ print $3 }')
    ACTUAL_KEY=$(ssh-keyscan -t "${KEY_TYPE}" "${HOST}" 2>&1 | tail -n1 | awk '{ print $3 }')
    if [ $? -ne 0 ]; then
        return 0
    fi

    if [ "${HOST_KEY}" != "${ACTUAL_KEY}" ]; then
        echo "remove changed host ${HOST}"
        ssh-keygen -R "${HOST}"
    fi
    return 0
}

# send file use scp
function send() {
    if [ $# -lt 3 ]; then
        echo "usage: send files - ip user(default root) path(default ~) passwd(default 123)"
        return -1
    fi

    args=($@)
    file_args=""
    declare -i i=0
    for arg in ${args[@]}; do
        if [ ${arg} == "-" ]; then
            i+=1
            break
        fi

        file_args+="${arg} "
        i+=1
    done

    declare -i j=0
    actual_args=("0" "root" "~" "123")
    remain_args=${args[@]:${i}}
    for arg in ${remain_args[@]}; do
        actual_args[${j}]="${arg}"
        j+=1
    done

    rm-changed-host "172.16.0.${actual_args[0]}"
    expect -c "
        spawn scp -r ${file_args} ${actual_args[1]}@172.16.0.${actual_args[0]}:${actual_args[2]}
        expect {
            \"yes/no\" {send \"yes\r\";exp_continue;}
            \"*password\" {set timeout 500;send \"${actual_args[3]}\r\";}
        }
    expect eof"
}
